#include "SFilterTermV.h"

#include <core/StyleMgr.h>

#include <QColor>
#include <QLineEdit>
#include <QStylePainter>

#include "SFilterButton.h"
#include "SFilterTermRange.h"

namespace {
const int gap = 4;
const int buttonHeight = 24;
}  // namespace

SFilterTermV::SFilterTermV(QWidget* p) : QFrame(p), m_nameWidth(0) {
  QVBoxLayout* layout = new QVBoxLayout(this);
  layout->setSpacing(gap);
  m_buttons = new SFilterButton(this);
  connect(m_buttons, &SFilterButton::tabSelected, this,
          &SFilterTermV::onFilterButtonClick);
  layout->addWidget(m_buttons);

  m_range = new SFilterTermRange(this);
  layout->addWidget(m_range);

  connect(m_range, &SFilterTermRange::changed, this,
          &SFilterTermV::onRangeChanged);
}

void SFilterTermV::setName(const QString& sName) {
  m_name = sName;
  if (m_name.isEmpty()) return;

  if (m_nameWidth <= 0) {
    QFontMetrics fmName(font());
    m_nameWidth = fmName.horizontalAdvance(m_name) + 16;
  }
  layout()->setContentsMargins(m_nameWidth + gap, 0, 0, 0);
}

void SFilterTermV::setNameWidth(int width) {
  m_nameWidth = width;
  layout()->setContentsMargins(m_nameWidth + gap, 0, 0, 0);
}

void SFilterTermV::addTab(const QString& name) {
  if (!m_buttons) return;
  m_buttons->addTab(name);
}

void SFilterTermV::selectTab(int index, bool bCtrlPress) {
  if (m_buttons) m_buttons->selectTab(index, bCtrlPress);
  if (m_range) m_range->clear();
}

int SFilterTermV::getTabCount() {
  if (!m_buttons) return 0;
  return m_buttons->getTabCount();
}

void SFilterTermV::getSelTab(std::vector<int>& vctSel) {
  if (!m_buttons) return;
  m_buttons->getSelTab(vctSel);
  return;
}

void SFilterTermV::getTermRange(QString& strStart, QString& strEnd,
                                bool& bDateMode) {
  m_range->getTermRange(strStart, strEnd, bDateMode);
}

void SFilterTermV::onFilterButtonClick() {
  if (!m_range) return;
  m_range->clear();
  emit filterChanged();
}

void SFilterTermV::onRangeChanged() {
  if (!m_buttons) return;
  m_buttons->clearSelect();
  emit filterChanged();
}

void SFilterTermV::paintEvent(QPaintEvent* event) {
  if (m_nameWidth <= 0) return;

  QStylePainter painter(this);
  QRect rc(0, 0, m_nameWidth, buttonHeight);
  QColor bkColor = NAME_COLOR("StaticTextBK");
  painter.setPen(Qt::NoPen);
  painter.setBrush(bkColor);
  painter.drawRoundedRect(rc, 2, 2);

  rc.setLeft(rc.left() + 8);
  painter.setPen(StyleMgr::instance().color("TitleWord"));
  painter.drawText(rc, m_name, QTextOption(Qt::AlignLeft | Qt::AlignVCenter));
}
